#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2002,2004 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
#
######################################################################
#                                                                    #
# Module: rmlcsext                                                   #
#                                                                    #
######################################################################
#                                                                    #
# Description: script to uninstall CSM/Director integration          #
#              extensions on CSM management servers and nodes        #
#                                                                    #
# Input:                                                             #
#   -A|--agemt   uninstall Director Agent and CSM/Director agent     #
#   -h|--help    show usage                                          #
#   -S|--server  uninstall Director Server components                #
#   -v|--verbose verbose output level                                #
#   --restart    restart IBM Director without prompting              #
#                                                                    #
# Output: None                                                       #
#                                                                    #
# External references:                                               #
#         rpm --query                                                #
#         rpm --erase                                                #
#                                                                    #
# Return codes:                                                      #
#    0: Success                                                      #
#  1-3: Number of packages that failed to install                    #
#   96: Error with IBM Director operation                            #
#   99: Parse Args Error                                             #
######################################################################
# sccsid = "@(#)95   1.17   src/csm/director/install/bin/rmlcsext.perl, csm.director, csm_rameh, rameh0431a 3/29/04 09:21:20"
use strict;
use locale;
use Getopt::Long;
use File::Basename;
use File::Spec::Functions;

BEGIN {
    $::csmpm = $ENV{'CSM_PM'} ? $ENV{'CSM_PM'} : '/opt/csm/pm';#development use
}

use lib dirname($0); # for CDROM  installs
use lib $::csmpm;    # for normal installs
use NodeUtils;
use DirectorUtils;

##################
# Global variables
##################
our $rcode     = 0;            # Script return code
our $rpm_rcode = 0;            # RPM call return code
our $verbose   = 0;            # Verbose flag
our $progname  = basename($0); # program name as invoked
our $progpath  = dirname($0);  # full path to running program

our $try_uninstall_agent  = 0;
our $try_uninstall_server = 0;
our $try_uninstall_everything = 0; # Uninstall all of above (default)

our $restart_director = -1; # Default, let user decide
our $director_stopped = 0;  # Did we stop Director agent?

our $packages_found = 0;      # Number of requested packages located
our $packages_removed = 0;    # Number actually removed

our $required_perl_version = 5.006001;

our $RPM = "/bin/rpm";
our $pkgs_to_query="csm.director.agent csm.director.server ITDAgent ITDServer";

# CSM Related paths
our $csmdir     = catdir(rootdir(), "opt", "csm");

# Messaging variables
our $MSGCAT = "csmdirector.cat"; # msg catalogue for this cmd
our $MSGMAPPATH; # Msg maps used by NodeUtils->message()
if ($ENV{'CSM_MSGMAP_PATH'}) {
    # use override provided by environment variable if set
    $MSGMAPPATH = $ENV{'CSM_MSGMAP_PATH'};
} elsif (-r catdir($progpath, "msgs", "csmdirector.common.map")) {
    # when running from CSM CD
    $MSGMAPPATH = catdir($progpath, "msgs");
} elsif (-r catdir($csmdir, "msgmaps", "csmdirector.common.map")) {
    # when running from csm.core install
    $MSGMAPPATH = catdir($csmdir, "msgmaps");
} elsif (-r catdir($progpath, ".nls/en", "csmdirector.common.map")) {
    # when running from csm.director.server install
    $MSGMAPPATH = catdir($progpath, ".nls/en");
} else { # shouldn't ever get here
    # resort /opt/csm/msgsmaps, even tho we know it will fail
    $MSGMAPPATH = catdir($csmdir, "msgmaps");
}

if ($verbose) {
    print         "Using \$MSGMAPPATH = $MSGMAPPATH\n";
}

our $director_server_name =
  NodeUtils->getMessageFromCat($MSGCAT, $MSGMAPPATH, 'common', "IMsgServer");
our $director_agent_name =
  NodeUtils->getMessageFromCat($MSGCAT, $MSGMAPPATH, 'common', "IMsgAgent");
our $restarted_name = $director_agent_name;  # Name of installed component


######################################################################
# usage:
#     display usage message and exit
######################################################################
sub usage {
    NodeUtils->message('I', "IMsgRmlcsextUsage", $progname);
}


######################################################################
# parse_args:
#     parse and verify command line arguments
######################################################################
sub parse_args {
    Getopt::Long::Configure("posix_default");
    Getopt::Long::Configure("bundling");
    Getopt::Long::Configure("no_gnu_compat");

    my ($help)    = '';

    if (!GetOptions(       "help|h" => \$help,
		       "verbose|v+" => \$verbose,
                         "restart!" => \$restart_director,

                           "agent!" => \$try_uninstall_agent,
                                "A" => \$try_uninstall_agent,

                          "server!" => \$try_uninstall_server,
                                "S" => \$try_uninstall_server))
    {
        usage(); exit(99);
    }

    if ($help) { usage(); exit(0); }

    $DirectorUtils::VERBOSE = $verbose;

    if (!$try_uninstall_agent && !$try_uninstall_server) {
        # if no options specified, try everything
        $try_uninstall_everything = 1;
    }
}


######################################################################
# set_defaults:
#     setup values of variables used
######################################################################
sub set_defaults {
}


######################################################################
# uninstall_rpm
#     locate RPM in searchpath and uninstall it
######################################################################
sub uninstall_rpm {
    my($pkgname) = @_;
    NodeUtils->messageFromCat($MSGCAT, $MSGMAPPATH, 'common','I',
                              "IMsgUninstallRPM", $progname, $pkgname);
    if ($verbose >= 3) {
        print         "$RPM --erase $pkgname  ... ";
    }
    my $inst_output = `$RPM --erase $pkgname`;
    my ($rc) = $? >> 8;
    if ($rc) {
        NodeUtils->messageFromCat($MSGCAT, $MSGMAPPATH, 'common',
                                  'I', "IMsgFailure");
        print("$inst_output\n");
        if ($rc > $rpm_rcode) { $rpm_rcode = $rc; }
    }
    else {
        NodeUtils->messageFromCat($MSGCAT, $MSGMAPPATH, 'common',
                                  'I', "IMsgSuccess");
    }
    return $rc;
}


######################################################################
# Mainline code
######################################################################
if ($] lt $required_perl_version) {
	# Do nothing if running with Perl below required Perl version
	exit 0;
}

&parse_args;   # parse command line
&set_defaults; # setup default values

our %INSTALLED = DirectorUtils::determine_installed_sw($pkgs_to_query);

if ($try_uninstall_server || $try_uninstall_everything) {
    if (exists $INSTALLED{"csm.director.server"}) {
        my $compname =
          NodeUtils->getMessageFromCat($MSGCAT, $MSGMAPPATH, 'common',
                                       "IMsgLCSserver");
        NodeUtils->message('I', "IMsgUninstallLCSComp", $progname, $compname);
	$restarted_name = $director_server_name;
        $packages_found++;
        if (!$director_stopped &&
	    (DirectorUtils::DirectorStatus() == 1 &&
             DirectorUtils::ask_stop_director($restarted_name)))
        {
            $director_stopped = 1;
            DirectorUtils::DirectorStop($restarted_name);
        }
        if (&uninstall_rpm("csm.director.server") == 0) {
            $packages_removed++;
        }
        else {
            $rcode++;
        }
    }
}

if ($try_uninstall_agent || $try_uninstall_everything) {
    if (exists $INSTALLED{"csm.director.agent"}) {
        my $compname =
          NodeUtils->getMessageFromCat($MSGCAT, $MSGMAPPATH, 'common',
                                       "IMsgLCSagent");
        NodeUtils->message('I', "IMsgUninstallLCSComp", $progname, $compname);
        $packages_found++;
        if (DirectorUtils::DirectorStatus() == 1 &&
            DirectorUtils::ask_stop_director($restarted_name))
        {
            $director_stopped = 1;
            DirectorUtils::DirectorStop($restarted_name);
        }
        if (&uninstall_rpm("csm.director.agent") == 0) {
            $packages_removed++;
        }
        else {
            $rcode++;
        }
    }
}

if ($director_stopped) {
    NodeUtils->messageFromCat($MSGCAT, $MSGMAPPATH, 'common','I', "IMsgDirectorRestarting", $progname, $restarted_name);
    DirectorUtils::DirectorStart();
}


if ($verbose) {
    NodeUtils->message('I', "IMsgRMsummary",
                       $progname, $packages_found, $packages_removed);
}

exit $rcode;
